package com.kun.framework.core.compoment;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.kun.framework.core.AbstractApplication;
import com.kun.framework.core.util.ComUtil;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * 弹窗信息
 *
 * @author gzc
 * @since 2024/8/8
 */
public class AlertMessage {
    private final static Logger log = LoggerFactory.getLogger(AlertMessage.class);

    public static Alert createDefaultAlert() {
        WeakReference<Alert> weakReference = new WeakReference<>(new Alert(Alert.AlertType.NONE));
        return weakReference.get();
    }

    public static Alert createAlert(Alert.AlertType alertType) {
        Alert alert = createAlert();
        alert.setAlertType(alertType);
        return alert;
    }

    public static Alert createAlert() {
        Alert alert = createDefaultAlert();
        alert.initStyle(StageStyle.UTILITY);
        alert.setTitle(null);
        alert.setHeaderText(null);
        alert.setGraphic(null);
        alert.getButtonTypes().clear();
        alert.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
        return alert;
    }


    /**
     * 警告弹窗
     *
     * @param msg      警告信息
     * @param consumer 按钮回调函数
     */
    public static void warning(String msg, Consumer<ButtonType> consumer) {
        // 主线程执行
        ComUtil.jfxThreadRun(() -> {
            WeakReference<Alert> weakReference = new WeakReference<>(new Alert(Alert.AlertType.NONE));
            Alert alert = weakReference.get();
            alert.initStyle(StageStyle.UTILITY);
            alert.setTitle("是否终止操作");
            alert.setHeaderText(null);
            alert.setContentText(msg);
            alert.getButtonTypes().add(ButtonType.OK);
            alert.getButtonTypes().add(ButtonType.CANCEL);
            alert.showAndWait().ifPresent(consumer);
        });
    }

    /**
     * 错误信息弹出框
     *
     * @param throwable 异常对象
     * @param exMsg     错误信息简述
     * @param params    参数数组
     */
    public static void error(Throwable throwable, String exMsg, Object... params) {
        error(StrUtil.format(exMsg, params), throwable, null);
    }

    public static void error(String exMsg, Throwable throwable) {
        error(exMsg, throwable, null);
    }

    /**
     * 错误信息弹出框
     *
     * @param exMsg     错误信息简述
     * @param throwable 异常对象
     */
    public static void error(String exMsg, Throwable throwable, Stage stage) {
        // 主线程执行
        ComUtil.jfxThreadRun(() -> {
            // 异常信息转字符串
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            String exceptionText = sw.toString();
            // 构建错误提示框
            Label label = new Label("详细异常信息如下：");
            TextArea textArea = new TextArea(exceptionText);
            // 是否可编辑
            textArea.setEditable(false);
            // 是否换行
            textArea.setWrapText(true);
            textArea.setMaxWidth(Double.MAX_VALUE);
            textArea.setMaxHeight(Double.MAX_VALUE);
            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);
            GridPane expContent = new GridPane();
            expContent.setMaxWidth(Double.MAX_VALUE);
            expContent.add(label, 0, 0);
            expContent.add(textArea, 0, 1);
            // 创建窗口
            Alert alert = createDefaultAlert();
            alert.setAlertType(Alert.AlertType.ERROR);
            alert.setTitle("错误提示");
            alert.setHeaderText("发生了异常");
            alert.setContentText(exMsg);
            // 在对话框窗格中设置可扩展异常
            alert.getDialogPane().setExpandableContent(expContent);
            alert.initOwner(stage == null ? AbstractApplication.getAppStage() : stage);
            // 展示异常窗口
            alert.showAndWait();
        });
    }

    public static void delete(List<String> deletePathList) {
        // 主线程执行
        ComUtil.jfxThreadRun(() -> {
            String collect = String.join("\n", deletePathList);
            TextArea textArea = new TextArea(collect);
            // 是否可编辑
            textArea.setEditable(false);
            // 是否换行
            textArea.setWrapText(true);
            textArea.setMaxWidth(400);
            textArea.setMaxHeight(400);
            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);
            // 创建窗口
            WeakReference<Alert> weakReference = new WeakReference<>(new Alert(Alert.AlertType.WARNING));
            Alert alert = weakReference.get();
            alert.setTitle("删除目录");
            alert.setHeaderText(null);
            alert.setWidth(400);
            alert.setHeight(400);
            alert.setContentText(collect);
            alert.getButtonTypes().clear();
            ButtonType bt1 = new ButtonType("删除");
            ButtonType bt2 = new ButtonType("取消");
            alert.getButtonTypes().addAll(bt1, bt2);
            // 展示异常窗口
            alert.showAndWait();

            List<String> errList = new ArrayList<>(128);
            List<String> successList = new ArrayList<>(128);
            for (ButtonType buttonType : alert.getButtonTypes()) {
                if (bt1.getText().equals(buttonType.getText())) {
                    for (String deletePath : deletePathList) {
                        if (StrUtil.isNotBlank(deletePath)) {
                            if (FileUtil.del(deletePath)) {
                                successList.add(deletePath);
                            } else {
                                errList.add(deletePath);
                            }
                        }
                    }
                    deletePathList.clear();
                    alert.close();
                }
                if (bt2.getText().equals(buttonType.getText())) {
                    alert.close();
                }
            }
            log.info("删除成功目录->{}", JSONUtil.toJsonPrettyStr(successList));
            log.warn("删除失败目录->{}", JSONUtil.toJsonPrettyStr(errList));
        });
    }
}
